package com.wcs.exam.dao.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wcs.exam.common.base.page.SqlUtil;
import com.wcs.exam.common.cache.CacheRedis;
import com.wcs.exam.common.constant.RedisConstant;
import com.wcs.exam.dao.PaperTitleDao;
import com.wcs.exam.dao.impl.mapper.PaperTitleMapper;
import com.wcs.exam.dao.impl.mapper.entity.PaperTitle;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 试卷标题 持久化实现类
 *
 * @author wcs
 * @since 2025-03-11
 */
@RequiredArgsConstructor
@Repository
public class PaperTitleDaoImpl extends ServiceImpl<PaperTitleMapper, PaperTitle> implements PaperTitleDao {

    @NotNull
    private final CacheRedis cacheRedis;

    @Override
    public <R> List<R> selectObjs(Wrapper<PaperTitle> wrapper, Class<R> classType) {
        List<Map<String, Object>> resultMaps = baseMapper.selectMaps(wrapper);
        if (CollectionUtil.isEmpty(resultMaps)) {
            return Collections.emptyList();
        }
        return BeanUtil.copyToList(resultMaps, classType);
    }

    @Override
    public Integer getMaxSort() {
        return lambdaQuery().orderByDesc(PaperTitle::getSort).last(SqlUtil.limitOne()).oneOpt().map(PaperTitle::getSort).orElse(0);
    }

    @Override
    public List<PaperTitle> listByPaperId(Long paperId) {
        return lambdaQuery()
                .eq(PaperTitle::getPaperId, paperId)
                .orderByAsc(PaperTitle::getSort, PaperTitle::getId)
                .list();
    }

    @Override
    public List<PaperTitle> listByPaperIdForCache(Long paperId) {
        List<PaperTitle> titles = cacheRedis.list(RedisConstant.Exam.PAPER_TITLE + paperId, PaperTitle.class);
        if (CollUtil.isEmpty(titles)) {
            titles = listByPaperId(paperId);
            cacheRedis.set(RedisConstant.Exam.PAPER_TITLE + paperId, titles, 10, TimeUnit.SECONDS);
        }
        return titles;
    }

    @Override
    public List<PaperTitle> sortListByIds(Collection<Long> ids) {
        return lambdaQuery()
                .in(PaperTitle::getId, ids)
                .orderByAsc(PaperTitle::getSort, PaperTitle::getId)
                .list();
    }

    @Override
    public Boolean deleteByPaperId(Long paperId) {
        return lambdaUpdate()
                .eq(PaperTitle::getPaperId, paperId)
                .remove();
    }

    @Override
    public Boolean deleteByPaperIds(Collection<Long> paperIds) {
        return lambdaUpdate()
                .in(PaperTitle::getPaperId, paperIds)
                .remove();
    }
}
